package com.weather;

import java.io.*;
import java.util.*;

import android.app.*;
import android.content.Context;
import android.view.*;
import android.widget.*;

/**
 * Adapter pentru afisarea listei de orase
 *
 */

public class CityAdapter extends BaseAdapter {
	
	private Activity context;
	private ArrayList<String> cities;
	private final static String SAVE = "cities.txt";

	public CityAdapter(Activity _context) {
		this.context = _context;
		cities = new ArrayList<String>();
	}

	@Override
	public int getCount() {
		return cities.size();
	}

	@Override
	public Object getItem(int pos) {
		return cities.get(pos);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup list)  {
		
		View element;
		if (convertView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			element = inflater.inflate(R.layout.city, null);
		} else
			element = convertView;

		TextView nume = (TextView) element.findViewById(R.id.city_name);
		nume.setText(cities.get(position));

		return element;
	}

	//Adauga un oras in lista. Salveaza in fisier
	public void addCity(String name) {
		cities.add(name);
		Collections.sort(cities);
		this.notifyDataSetChanged();
		saveList();
	}
	
	public void remove(int pos) {
		cities.remove(pos);
		this.notifyDataSetChanged();
	}
	
	//Salveaza lista de orase intr-un fisier
	public void saveList() {
			try {
				OutputStreamWriter out = new OutputStreamWriter(context.openFileOutput(SAVE, Context.MODE_PRIVATE));
				for(String str : cities){ 
					out.write(str);
					out.write("\n");
				}
				out.close();
			} catch(Throwable t) {}
	}
	
	//Citeste lista de orase din fisier
	public void loadList() {
			try {
				BufferedReader in = new BufferedReader(new InputStreamReader(context.openFileInput(SAVE)));
				cities.clear();				
				while(in.ready())
					cities.add(in.readLine());
				in.close();
			} catch(Throwable t) {}
	}
}
